package com.xdq.educenter.controller;

import com.google.gson.Gson;
import com.xdq.commonutils.JwtUtils;
import com.xdq.educenter.entity.UcenterMember;
import com.xdq.educenter.service.UcenterMemberService;
import com.xdq.educenter.utils.ConstanWxtiesUtil;
import com.xdq.educenter.utils.HttpClientUtils;
import com.xdq.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    @GetMapping("callback")
    public String callback(String code, String state) throws GuliException {
        System.out.println("code:" + code);
        System.out.println("state:" + state);

        try {
            // 2 拿着 code 请求微信固定的地址，得到 accsess_token 和 openId
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            // 拼接
            String accessTokenUri = String.format(baseAccessTokenUrl,
                    ConstanWxtiesUtil.WX_OPEN_APP_ID,
                    ConstanWxtiesUtil.WX_OPEN_APP_SECRET,
                    code
            );
            String accessTokenInfo = HttpClientUtils.get(accessTokenUri);
            System.out.println("accessTokenInfo:" + accessTokenInfo);
            // json 转换 取出 access_token 和 openid
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");

            UcenterMember member = memberService.getOpenIdMember(openid);
            if (member == null) {
                // 3 拿着 access_token 和 openid 请求微信固定的地址，得到 用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("userInfo:" + userInfo);
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nackame = (String) userInfoMap.get("nickname");
                String headimgurl = (String) userInfoMap.get("headimgurl");

                // 将扫描人信息添加数据库
                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nackame);
                member.setAvatar(headimgurl);
                memberService.save(member);

                // 生成 token
                String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
                return "redirect:http://localhost:3000?token=" + jwtToken;
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "登录失败");
        }

        return "redirect:http://localhost:3000";
    }


    @GetMapping("login")
    public String getWxCode() throws UnsupportedEncodingException {
        // 微信开放平台授权baseUrl
        //? %s相当于占位符，可以填充参数
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //授权码需要传入加密过的URL,必须使用
        String redirectUrl = ConstanWxtiesUtil.WX_OPEN_REDIRECT_URL;//获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");//url编码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //设置%s参数值
        String url = String.format(
                baseUrl,
                ConstanWxtiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu");
        //请求微信地址,重定向的方式
        return "redirect:" + url;
    }
}
